using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace SimpleTaskbarCountdown
{
    public partial class MainForm : Form
    {
        private NotifyIcon notifyIcon;
        private Timer timer;
        private string lastDisplayedText = "";
        private Color lastDisplayedColor = Color.Black;
        private TimeSpan wakeUpTime = new TimeSpan(7, 0, 0); // 新增起床时间
        private TimeSpan lunchTime = new TimeSpan(12, 0, 0);
        private TimeSpan offWorkTime = new TimeSpan(18, 0, 0);
        private TimeSpan sleepTime = new TimeSpan(22, 0, 0);
        private string settingsFile = "countdown_settings.txt";

        public MainForm()
        {
            LoadSettings();
            InitializeComponent();
            InitializeTrayIcon();
            InitializeTimer();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // MainForm
            // 
            this.ClientSize = new System.Drawing.Size(1, 1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "MainForm";
            this.ShowInTaskbar = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            this.ResumeLayout(false);
        }

        private void LoadSettings()
        {
            try
            {
                if (File.Exists(settingsFile))
                {
                    string[] lines = File.ReadAllLines(settingsFile);
                    if (lines.Length >= 1) wakeUpTime = TimeSpan.Parse(lines[0]);
                    if (lines.Length >= 2) lunchTime = TimeSpan.Parse(lines[1]);
                    if (lines.Length >= 3) offWorkTime = TimeSpan.Parse(lines[2]);
                    if (lines.Length >= 4) sleepTime = TimeSpan.Parse(lines[3]);
                }
            }
            catch
            {
                // 使用默认设置
            }
        }

        private void SaveSettings()
        {
            try
            {
                File.WriteAllText(settingsFile, $"{wakeUpTime}\n{lunchTime}\n{offWorkTime}\n{sleepTime}");
            }
            catch { }
        }

        private void InitializeTrayIcon()
        {
            notifyIcon = new NotifyIcon();
            notifyIcon.Text = "倒计时应用";
            notifyIcon.Visible = true;

            ContextMenuStrip contextMenu = new ContextMenuStrip();

            ToolStripMenuItem settingsItem = new ToolStripMenuItem("设置时间");
            settingsItem.Click += OpenSettings;
            contextMenu.Items.Add(settingsItem);

            ToolStripMenuItem exitItem = new ToolStripMenuItem("退出");
            exitItem.Click += OnExit;
            contextMenu.Items.Add(exitItem);

            notifyIcon.ContextMenuStrip = contextMenu;
            notifyIcon.DoubleClick += OpenSettings;
        }

        private void InitializeTimer()
        {
            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += UpdateCountdown;
            timer.Start();
            UpdateCountdown(null, EventArgs.Empty);
        }

        private void OpenSettings(object sender, EventArgs e)
        {
            using (SettingsForm settings = new SettingsForm())
            {
                settings.WakeUpTime = wakeUpTime.ToString(@"hh\:mm");
                settings.LunchTime = lunchTime.ToString(@"hh\:mm");
                settings.OffWorkTime = offWorkTime.ToString(@"hh\:mm");
                settings.SleepTime = sleepTime.ToString(@"hh\:mm");

                if (settings.ShowDialog() == DialogResult.OK)
                {
                    if (TimeSpan.TryParse(settings.WakeUpTime, out TimeSpan newWakeUp))
                        wakeUpTime = newWakeUp;

                    if (TimeSpan.TryParse(settings.LunchTime, out TimeSpan newLunch))
                        lunchTime = newLunch;

                    if (TimeSpan.TryParse(settings.OffWorkTime, out TimeSpan newOffWork))
                        offWorkTime = newOffWork;

                    if (TimeSpan.TryParse(settings.SleepTime, out TimeSpan newSleep))
                        sleepTime = newSleep;

                    SaveSettings();
                    UpdateCountdown(null, EventArgs.Empty);
                }
            }
        }

        private void UpdateCountdown(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            DateTime wakeUpToday = now.Date.Add(wakeUpTime);
            DateTime lunchToday = now.Date.Add(lunchTime);
            DateTime offWorkToday = now.Date.Add(offWorkTime);
            DateTime sleepToday = now.Date.Add(sleepTime);
            DateTime nextTarget;

            // 确定下一个目标时间
            if (now < wakeUpToday)
            {
                nextTarget = wakeUpToday;
            }
            else if (now < lunchToday)
            {
                nextTarget = lunchToday;
            }
            else if (now < offWorkToday)
            {
                nextTarget = offWorkToday;
            }
            else if (now < sleepToday)
            {
                nextTarget = sleepToday;
            }
            else
            {
                // 明天起床时间
                nextTarget = now.Date.AddDays(1).Add(wakeUpTime);
            }

            TimeSpan remaining = nextTarget - now;
            string displayText;
            Color textColor = GetTimePeriodColor(now);
            string tooltipText;

            if (remaining.TotalHours < 1)
            {
                int minutes = (int)remaining.TotalMinutes;
                displayText = minutes.ToString();
                tooltipText = $"倒计时: {minutes}分钟";
            }
            else
            {
                displayText = remaining.TotalHours.ToString("0.0");
                tooltipText = $"倒计时: {displayText}小时";
            }

            notifyIcon.Text = tooltipText;

            if (displayText != lastDisplayedText || textColor != lastDisplayedColor)
            {
                Icon newIcon = CreateTextIcon(displayText, textColor);
                if (notifyIcon.Icon != null)
                {
                    notifyIcon.Icon.Dispose();
                }
                notifyIcon.Icon = newIcon;

                lastDisplayedText = displayText;
                lastDisplayedColor = textColor;
            }
        }

        private Color GetTimePeriodColor(DateTime now)
        {
            TimeSpan currentTime = now.TimeOfDay;

            if (currentTime >= wakeUpTime && currentTime < lunchTime)
            {
                return Color.Green; // 上午绿色
            }
            else if (currentTime >= lunchTime && currentTime < offWorkTime)
            {
                return Color.Orange; // 下午橙色
            }
            else if (currentTime >= offWorkTime && currentTime < sleepTime)
            {
                return Color.Blue; // 晚上蓝色
            }
            else
            {
                return Color.Gray; // 睡觉时间灰色
            }
        }

        private Icon CreateTextIcon(string text, Color color)
        {
            using (Bitmap bitmap = new Bitmap(48, 48))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.Clear(Color.Transparent);
                    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                    float fontSize;
                    if (text.Length <= 3)
                    {
                        fontSize = 36;
                    }
                    else if (text.Length == 4)
                    {
                        fontSize = 27;
                    }
                    else
                    {
                        fontSize = 26;
                    }

                    Font font = new Font("Arial", fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
                    SizeF textSize = g.MeasureString(text, font);
                    float x = (bitmap.Width - textSize.Width) / 2;
                    float y = (bitmap.Height - textSize.Height) / 2;

                    g.DrawString(text, font, Brushes.Black, x + 1, y + 1);
                    g.DrawString(text, font, new SolidBrush(color), x, y);
                }

                return Icon.FromHandle(bitmap.GetHicon());
            }
        }

        private void OnExit(object sender, EventArgs e)
        {
            notifyIcon.Visible = false;
            if (notifyIcon.Icon != null)
            {
                notifyIcon.Icon.Dispose();
            }
            Application.Exit();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.Visible = false;
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }

    public class SettingsForm : Form
    {
        private TextBox txtWakeUp;
        private TextBox txtLunch;
        private TextBox txtOffWork;
        private TextBox txtSleep;
        private Button btnSave;
        private Button btnCancel;
        private Label label0;
        private Label label1;
        private Label label2;
        private Label label3;

        public string WakeUpTime { get; set; }
        public string LunchTime { get; set; }
        public string OffWorkTime { get; set; }
        public string SleepTime { get; set; }

        public SettingsForm()
        {
            InitializeComponents();
            this.Load += SettingsForm_Load;
        }

        private void SettingsForm_Load(object sender, EventArgs e)
        {
            txtWakeUp.Text = WakeUpTime ?? "07:00";
            txtLunch.Text = LunchTime ?? "12:00";
            txtOffWork.Text = OffWorkTime ?? "18:00";
            txtSleep.Text = SleepTime ?? "22:00";
        }

        private void InitializeComponents()
        {
            this.Size = new Size(320, 320); // 增加高度以容纳第四个设置
            this.Text = "设置倒计时时间";
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 起床时间
            label0 = new Label();
            label0.Text = "起床时间 (HH:mm):";
            label0.Location = new Point(20, 30);
            label0.Size = new Size(140, 25);
            label0.Font = new Font(label0.Font.FontFamily, 10);

            txtWakeUp = new TextBox();
            txtWakeUp.Location = new Point(170, 30);
            txtWakeUp.Size = new Size(120, 30);
            txtWakeUp.Font = new Font(txtWakeUp.Font.FontFamily, 10);

            // 午休时间
            label1 = new Label();
            label1.Text = "午休时间 (HH:mm):";
            label1.Location = new Point(20, 80);
            label1.Size = new Size(140, 25);
            label1.Font = new Font(label1.Font.FontFamily, 10);

            txtLunch = new TextBox();
            txtLunch.Location = new Point(170, 80);
            txtLunch.Size = new Size(120, 30);
            txtLunch.Font = new Font(txtLunch.Font.FontFamily, 10);

            // 下班时间
            label2 = new Label();
            label2.Text = "下班时间 (HH:mm):";
            label2.Location = new Point(20, 130);
            label2.Size = new Size(140, 25);
            label2.Font = new Font(label2.Font.FontFamily, 10);

            txtOffWork = new TextBox();
            txtOffWork.Location = new Point(170, 130);
            txtOffWork.Size = new Size(120, 30);
            txtOffWork.Font = new Font(txtOffWork.Font.FontFamily, 10);

            // 睡觉时间
            label3 = new Label();
            label3.Text = "睡觉时间 (HH:mm):";
            label3.Location = new Point(20, 180);
            label3.Size = new Size(140, 25);
            label3.Font = new Font(label3.Font.FontFamily, 10);

            txtSleep = new TextBox();
            txtSleep.Location = new Point(170, 180);
            txtSleep.Size = new Size(120, 30);
            txtSleep.Font = new Font(txtSleep.Font.FontFamily, 10);

            // 按钮
            btnSave = new Button();
            btnSave.Text = "保存";
            btnSave.Location = new Point(80, 230);
            btnSave.Size = new Size(80, 35);
            btnSave.Font = new Font(btnSave.Font.FontFamily, 10);
            btnSave.Click += BtnSave_Click;

            btnCancel = new Button();
            btnCancel.Text = "取消";
            btnCancel.Location = new Point(170, 230);
            btnCancel.Size = new Size(80, 35);
            btnCancel.Font = new Font(btnCancel.Font.FontFamily, 10);
            btnCancel.Click += BtnCancel_Click;

            // 添加控件
            this.Controls.Add(label0);
            this.Controls.Add(txtWakeUp);
            this.Controls.Add(label1);
            this.Controls.Add(txtLunch);
            this.Controls.Add(label2);
            this.Controls.Add(txtOffWork);
            this.Controls.Add(label3);
            this.Controls.Add(txtSleep);
            this.Controls.Add(btnSave);
            this.Controls.Add(btnCancel);
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            WakeUpTime = txtWakeUp.Text;
            LunchTime = txtLunch.Text;
            OffWorkTime = txtOffWork.Text;
            SleepTime = txtSleep.Text;

            if (IsValidTime(WakeUpTime) && IsValidTime(LunchTime) &&
                IsValidTime(OffWorkTime) && IsValidTime(SleepTime))
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("请输入有效的时间格式 (HH:mm)\n例如: 07:00, 12:00, 18:00, 22:00", "格式错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool IsValidTime(string time)
        {
            return TimeSpan.TryParse(time, out _);
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}